package com.shxy.rlzy.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.shxy.rlzy.common.lang.Const;
import com.shxy.rlzy.common.lang.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: rlzy
 * @description: 验证控制器
 * @author: tanhao
 * @create: 2021-08-17 21:46
 */
@RestController
public class AuthController extends BaseController {

    private Producer producer;

    @Autowired
    public void setProducer(Producer producer) {
        this.producer = producer;
    }

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        // 生成key和code
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 根据code生成图片并转换成base64格式字符串
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64Encoder.encode(outputStream.toByteArray());

        // 将key和code放入redis
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        // 返回key和base64格式图片字符串
        return Result.succ(MapUtil.builder().put("captchaKey", key).put("captchaImg", base64Img).build());
    }
}
